package top.lywivan.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.basePath}")
    private String basePath;
    /**
     * 实现图片文件的上传功能
     * @param file 用户上传的文件对象
     * @return
     */
    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        //如果文件夹不存在则创建文件夹
        if (!new File(basePath).exists()){
            new File(basePath).mkdirs();
        }
        String originalFilename = file.getOriginalFilename();
        //log.info("开始上传文件：{}",originalFilename);
        String fileName= UUID.randomUUID().toString().replace("-","")+originalFilename.substring(originalFilename.lastIndexOf("."));
        file.transferTo(new File(basePath,fileName));
        return R.success(fileName);
    }

    /**
     * 实现图片的下载回显功能
     * @param name 前端需要的图片名称
     * @return
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        //log.info("开始回显图片：{}",name);
        File file = new File(basePath, name);
        FileInputStream fis = new FileInputStream(file);
        ServletOutputStream sos = response.getOutputStream();
        IOUtils.copy(fis,sos);
        fis.close();
    }
}
